package com.gxa.meiye.admin.Interceptor;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.gxa.meiye.admin.thread.UserThreadLocal;
import com.gxa.meiye.core.exception.BusinessException;
import com.gxa.meiye.core.exception.ExceptionCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;


@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    RestTemplate restTemplate;
    //前置处理器,拦截token
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取token
        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)){
           throw new BusinessException(ExceptionCode.EMPTY_TOKEN);
        }
        System.out.println(token);
        //url
        String url = "http://1.117.60.194:8082/mlstherapist/checkToken";
        //请求头（包括请求类型）
        HttpHeaders httpHeaders = new HttpHeaders();
        //MediaType.APPLICATION_FORM_URLENCODED对应于 @RequestParam传参
        //MediaType.APPLICATION_JSON 对应 @RequestBody传参
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        //请求参数
        //Spring提供的工具类可以一次传递多个参数
        //服务器之间传参将token以参数传递
        MultiValueMap<String,String> multiValueMap = new LinkedMultiValueMap<>();
        multiValueMap.add("token",token);
        //请求类型
        //HttpEntity:Spring提供的一个传递http请求的实体类型
        HttpEntity httpEntity = new HttpEntity(multiValueMap,httpHeaders);
        //通过post方法发送请求
        Map map = restTemplate.postForObject(url, httpEntity, Map.class);
        if(!map.get("code").equals("1")){
            return false;
        }

        //将user对象转换为json返回前端,将拦截器里的对象放在threadLocal里，而不应该直接返回给前端
        Object data = map.get("data");
        ObjectMapper objectMapper = new ObjectMapper();
         String jsonString = objectMapper.writeValueAsString(data);
         System.out.println(jsonString);
        //将返回的数据放在threadlocal
        UserThreadLocal.set(jsonString);
//        PrintWriter printWriter = response.getWriter();
//        printWriter.write(jsonString);
//        printWriter.flush();
//        printWriter.close();
        return true;
    }
}
